package com.jack.helloworld.util;

import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;

import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/6/13.
 */
public class SystemUtil {

    public static String getBuildVersion() {
        String buildVersion = MySystemProperties.get("ro.build.verno");
        buildVersion = StringUtils.isBlank(buildVersion) ? Build.DISPLAY : buildVersion;
        return buildVersion;
    }

    public static String getProduct() {
        String product = MySystemProperties.get("ro.build.product");
        product = product == null ? "" : product;
        return product;
    }


    // 获取android id
    public static String getAndroidID(Context context) {
        ContentResolver cr = context.getContentResolver();
        String androidId = Settings.System.getString(cr,
                Settings.Secure.ANDROID_ID);
        if (androidId == null) {
            androidId = "000000";
        }
        return androidId;
    }

    //获取mac
    public static String getWifiMac(Context context) {
        String mac = "";
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager == null) {
            return null;
        }

        WifiInfo wifiConnInfo = null;
        if (wifiManager.getWifiState() != WifiManager.WIFI_STATE_UNKNOWN) {
            wifiConnInfo = wifiManager.getConnectionInfo();
            mac = wifiConnInfo.getMacAddress();
        }

        if (mac == null) {
            return "";
        }

        //Logger.d("SystemUtil#getWifiMac#mac: " + mac);
        String str = mac.replace(":", "").toString().toLowerCase();
        if (str.matches("(\\p{XDigit})\\1{11}") || str.endsWith("020000000000")) {
            mac = getMacOnFile();
            Logger.d("SystemUtil#getMacOnFile#mac: " + mac);
        }

        return mac;
    }

    //6.0获取mac
    private static String getMacOnFile() {
        String mac = null;
        String wifiDir = MySystemProperties.get("wifi.interface");
        File path = new File("/sys/class/net/" + wifiDir + "/address");
        int count = 20;// 20*200=4s
        while (!path.exists() && count-- > 0) {
            try {
                Logger.d("SystemUtil#getMacOnFile#sleep(200): " + count);
                Thread.sleep(200);
            } catch (InterruptedException e) {
            }
        }
        if (!path.exists()) {
            return mac;
        }
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path);
            byte[] buff = new byte[32];
            int len = fis.read(buff);
            mac = new String(buff, 0, len).trim()/*.replace(":", "")*/.toLowerCase();
        } catch (FileNotFoundException e) {
            Logger.e(e, "SystemUtil#getMacOnFile#ERR: " + e.getMessage());
        } catch (IOException e) {
            Logger.e(e, "SystemUtil#getMacOnFile#ERR: " + e.getMessage());
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                }
            }
        }
        Logger.d("SystemUtil#getMacOnFile#file: " + path.getAbsolutePath());
        return mac;
    }


    //获取IMEI
    public static String getImei(Context context) {
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String imei = null;
        if (tm != null) {
            try {
                imei = tm.getDeviceId();
            } catch (Exception e) {
                Logger.e(e, "SystemUtil#getImei#ERR: " + e.getMessage());
            }
        }
        return imei;
    }

    //获取IMSI
    public static String getImsi(Context context) {
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (tm == null) {
            return null;
        }
        String imsi = null;
        try {
            imsi = tm.getSubscriberId();
            if (imsi == null) {
                imsi = tm.getSimOperator();
            }
        } catch (Exception e) {
            Logger.e(e, "SystemUtil#getImsi#ERR: " + e.getMessage());
        }
        return imsi;
    }

    //获取语言环境
    public static String getLocale(Context context) {
        String language = context.getResources().getConfiguration().locale.getLanguage();
        String country = context.getResources().getConfiguration().locale.getCountry();
        return (language + Constants.MINUS + country);
    }

    //获取CPU硬件名
    public static String getCpuHardware() {
        String cpuSerial = null;
        try {
            Process pp = Runtime.getRuntime().exec("cat /proc/cpuinfo");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            String str = "";
            while ((str = input.readLine()) != null) {
                if (str.indexOf("Hardware") != -1) {
                    String[] str2 = str.split("\\s+");
                    cpuSerial = str2[2];
                }
            }
        } catch (IOException e) {
            Logger.e(e, "SystemUtil#getCpuHardware#ERR: " + e.getMessage());
        }
        return cpuSerial;
    }

    //是否WIFI
    public static int getNetState(Context context) {
        // 获取wifi状态 1 wifi 0 其他
        int netState = 0;
        ConnectivityManager con = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo.State state = con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        if (NetworkInfo.State.CONNECTED == state) {
            netState = 1;
        }
        return netState;
    }

    //检测网络是否连接
    public static boolean isNetworkAvailable(Context context) {
        try {
            //得到网络连接信息
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (manager != null) {
                // 获取NetworkInfo对象
                NetworkInfo networkInfo = manager.getActiveNetworkInfo();
                //去进行判断网络是否连接
                if (networkInfo != null && networkInfo.isAvailable()) {
                    return true;
                }
            }
        } catch (Exception e) {
            Logger.e(e, "SystemUtil#isNetworkAvailable#ERR: " + e.getMessage());
        }
        return false;
    }

    //获取SIM卡状态
    public static int getSimState(Context context) {

        int simalive = 0;

        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);

        int simState = -1;
        if (tm != null) {
            try {
                simState = tm.getSimState();
            } catch (Exception e) {
                Logger.e(e, "SystemUtil#getImei#ERR: " + e.getMessage());
            }
        }

        switch (simState) {
            case TelephonyManager.SIM_STATE_ABSENT:
                simalive = 0;
                break;
            case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
                simalive = 0;
                break;
            case TelephonyManager.SIM_STATE_PIN_REQUIRED:
                simalive = 0;
                break;
            case TelephonyManager.SIM_STATE_PUK_REQUIRED:
                simalive = 0;
                break;
            case TelephonyManager.SIM_STATE_READY:
                simalive = 1;
                break;
            case TelephonyManager.SIM_STATE_UNKNOWN:
                simalive = 0;
                break;
        }

        return simalive;
    }

    //获取第三方应用信息
    public static List<PackageInfo> getThirdPackageInfo(Context context) {
        List<PackageInfo> apps = new ArrayList<PackageInfo>();
        List<PackageInfo> _listApplicationInfos = getAllPackages(context);
        for (PackageInfo packageInfo : _listApplicationInfos) {
            if (((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0)) {
                apps.add(packageInfo);
            } else if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
                apps.add(packageInfo);
            }
        }
        return apps;
    }

    //获取所有应用信息
    public static List<PackageInfo> getAllPackages(Context context) {
        return context.getPackageManager().getInstalledPackages(0);
    }

    //获取所有包名，用“，”分隔
    public static String getPackageNames(Context context) {
        List<PackageInfo> allApk = SystemUtil.getThirdPackageInfo(context);
        if (allApk != null && allApk.size() > 0) {
            String pkgName = "";
            for (PackageInfo app : allApk) {
                pkgName += app.packageName + Constants.COMMA;
            }
            return pkgName.substring(0, pkgName.lastIndexOf(Constants.COMMA));
        }
        return "";
    }

}
